package com.comtop.springboot.templet.modules.sys.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.comtop.springboot.templet.modules.sys.entity.SysUserRoleEntity;
import com.comtop.springboot.templet.modules.sys.mapper.SysUserRoleMapper;
import com.comtop.springboot.templet.modules.sys.service.ISysUserRoleService;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 用户与角色对应关系
 * 
 * @author wangjiafang
 * @version 1.0
 * @since 2016年9月18日 上午9:45:48
 */
@Service("sysUserRoleService")
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper,SysUserRoleEntity> implements ISysUserRoleService {
	/**用户-角色关系服务**/
	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;

	@Override
	@Transactional
	public void saveOrUpdate(Long userId, List<Long> roleIdList) {
		if(roleIdList.size() == 0){
			return ;
		}
		
		//先删除用户与角色关系
		sysUserRoleMapper.delete(new EntityWrapper<SysUserRoleEntity>().eq("user_id",userId));
		
		//保存用户与角色关系
		//Map<String, Object> map = new HashMap<>();
		//map.put("userId", userId);
		//map.put("roleIdList", roleIdList);
		//sysUserRoleMapper.save(map);

		List<SysUserRoleEntity> sysUserRoleEntities = new ArrayList<>(roleIdList.size());
		SysUserRoleEntity sysUserRoleEntity=null;
		for (long roleId:roleIdList){
			sysUserRoleEntity = new SysUserRoleEntity();
			sysUserRoleEntity.setUserId(userId);
			sysUserRoleEntity.setRoleId(roleId);
			sysUserRoleEntities.add(sysUserRoleEntity);
		}
		insertBatch(sysUserRoleEntities);


	}

	@Override
	public List<Long> queryRoleIdList(Long userId) {
		return sysUserRoleMapper.queryRoleIdList(userId);
	}

	@Override
	public void delete(Long userId) {
		sysUserRoleMapper.delete(new EntityWrapper<SysUserRoleEntity>().eq("user_id",userId));
	}
}
